// src/stores/UserStore.js
import { defineStore } from 'pinia'
import { getUserInfo } from '@/api/User'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    initialized: false
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  
  actions: {
    async setUserInfo(data) {
      try {
        this.userInfo = data
        localStorage.setItem('userInfo', JSON.stringify(data))
      } catch (error) {
        console.error('保存用户信息失败:', error)
        ElMessage.error('保存用户信息失败')
      }
    },

    setToken(token) {
      try {
        this.token = token
        localStorage.setItem('token', token)
      } catch (error) {
        console.error('保存token失败:', error)
        ElMessage.error('保存登录状态失败')
      }
    },

    logout() {
      try {
        this.userInfo = null
        this.token = null
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
      } catch (error) {
        console.error('登出失败:', error)
        ElMessage.error('登出失败')
      }
    },

    async initializeFromStorage() {
      if (this.initialized) return

      try {
        const token = localStorage.getItem('token')
        const userInfoStr = localStorage.getItem('userInfo')
        
        if (!token || !userInfoStr) {
          this.logout()
          return
        }

        const userInfo = JSON.parse(userInfoStr)
        this.token = token
        this.userInfo = userInfo

        // 刷新用户信息
        if (userInfo.userId) {
          const res = await getUserInfo(userInfo.userId)
          if (res.status === 'success') {
            await this.setUserInfo(res.data)
          } else {
            throw new Error(res.message || '获取用户信息失败')
          }
        }

      } catch (error) {
        console.error('初始化用户状态失败:', error)
        this.logout()
        ElMessage.error('登录状态已过期，请重新登录')
      } finally {
        this.initialized = true
      }
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['userInfo', 'token','initialized']
      }
    ]
  }
})